import { routerRedux } from 'dva/router';
import { fakeAccountLogin ,AccountLogout} from '../services/api';

export default {
  namespace: 'login',

  state: {
    status: false,
    userInfo: {
    },
    error:'',
    submitting:false
  },

  effects: {
    *accountSubmit({ payload }, { call, put }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      yield put({
        type: 'changeSubmitting',
        payload:false,
      });
    },
    /**mobileSubmit(_, { call, put }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(fakeMobileLogin);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
    },*/
    *logout(_, { put,call}) {
      yield call(AccountLogout);
      localStorage.token='';
      yield put({
        type: 'changeLoginStatus',
        payload: {
          result: false,
        },
      });
      yield put(routerRedux.push('/index'));
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (state && payload.result) {
        let data = payload.data;
        localStorage.token = data.token;
      }else{
        localStorage.token='';
      }
      let msg=payload.msg || '';
      return {
        ...state,
        status: payload.result ,
        userInfo: payload.data || {},
        error: payload.result? '' :msg,
        type: payload.type || 'account',
      };
    },
    changeSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },
  },
};
